package com.momochen.client;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

import java.util.Date;

import static com.momochen.demo.ServiceTcpHandler.bytesToHexString;

/**
 * @author 徐飞
 * @version 2016/02/25 14:11
 */
public class NettyClientHandler extends SimpleChannelInboundHandler {
    //设置心跳时间  开始
    public static final int MIN_CLICK_DELAY_TIME = 1000 * 30;
    private long lastClickTime = 0;
    //设置心跳时间   结束

    //利用写空闲发送心跳检测消息
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
//                    long currentTime = System.currentTimeMillis();
//                    if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
//                        lastClickTime = System.currentTimeMillis();
//                        PingMsg pingMsg = new PingMsg();
//                        ctx.writeAndFlush(GsonUtlis.getGson().toJson(pingMsg));
//                        System.out.println("send ping to server----------");
//                    }
                    break;
                default:
                    break;
            }
        }
    }

    //这里是断线要进行的操作
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("重连了。---------");
        NettyClientBootstrap bootstrap = PushClient.getBootstrap();
        bootstrap.startNetty();
    }

    //这里是出现异常的话要进行的操作
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("出现异常了。。。。。。。。。。。。。");
        cause.printStackTrace();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        if (msg == null) {
//            System.out.println(sdf.format(new Date()) + "===> NULL ");
            return;
        }
        byte[] req = (byte[]) msg;
        System.out.println("===>" + bytesToHexString(req,10));
        ReferenceCountUtil.release(msg);
    }
}
